package com.jie.jie.Gesture;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Xfermode;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.jie.jie.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jie on 2017/5/8.
 */

public class GestureGroup extends RelativeLayout {
    private int mTryMaxTimes;
    private int mMarginBetweenLockView;
    private int mLastPathX;
    private int mLastPathY;

    public enum Mode {
        STATUS_NO_FINGER, STATUS_FINGER_ON, STATUS_FINGER_UP;
    }

    public ImageView[][] imageViews;
    public ImageView[][] newViews;
    private int mCount = 3;
    private Paint mPaint;
    private Path mPath;
    private int mHeight, mWidth;
    /**
     * 指引下的结束位置
     */
    private Point mTmpTarget = new Point();

    /**
     * GestureLockView无手指触摸的状态下内圆的颜色
     */
    private int mNoFingerInnerCircleColor = 0xFF939090;
    /**
     * GestureLockView无手指触摸的状态下外圆的颜色
     */
    private int mNoFingerOuterCircleColor = 0xFFE0DBDB;
    /**
     * GestureLockView手指触摸的状态下内圆和外圆的颜色
     */
    private int mFingerOnColor = 0xFF378FC9;
    /**
     * GestureLockView的边长 4 * mWidth / ( 5 * mCount + 1 )
     */
    private int mGestureLockViewWidth;
    /**
     * GestureLockView手指抬起的状态下内圆和外圆的颜色
     */
    private int mFingerUpColor = 0xFFFF0000;

    /**
     * 用户选中的点集合
     */
    private List<Integer> mChoose;


    public GestureGroup(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GestureGroup(Context context, AttributeSet attrs,
                        int defStyle) {
        super(context, attrs, defStyle);
        /**
         * 获得所有自定义的参数的值
         */
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
                R.styleable.GestureLockViewGroup, defStyle, 0);
        int n = a.getIndexCount();

        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            switch (attr) {
                case R.styleable.GestureLockViewGroup_color_no_finger_inner_circle:
                    mNoFingerInnerCircleColor = a.getColor(attr,
                            mNoFingerInnerCircleColor);
                    break;
                case R.styleable.GestureLockViewGroup_color_no_finger_outer_circle:
                    mNoFingerOuterCircleColor = a.getColor(attr,
                            mNoFingerOuterCircleColor);
                    break;
                case R.styleable.GestureLockViewGroup_color_finger_on:
                    mFingerOnColor = a.getColor(attr, mFingerOnColor);
                    break;
                case R.styleable.GestureLockViewGroup_color_finger_up:
                    mFingerUpColor = a.getColor(attr, mFingerUpColor);
                    break;
                case R.styleable.GestureLockViewGroup_count:
                    mCount = a.getInt(attr, 3);
                    break;
                case R.styleable.GestureLockViewGroup_tryTimes:
                    mTryMaxTimes = a.getInt(attr, 5);
                default:
                    break;
            }
        }
        a.recycle();
        // 初始化画笔
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        Xfermode avoid = new PorterDuffXfermode(PorterDuff.Mode.DARKEN);
        mPaint.setXfermode(avoid);
        mPaint.setStyle(Paint.Style.STROKE);
         mPaint.setStrokeWidth(5);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
         mPaint.setColor(Color.parseColor("#aaffffff"));
        mPath = new Path();
        if (mChoose == null) {
            mChoose = new ArrayList() ;

        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mWidth = MeasureSpec.getSize(widthMeasureSpec);
        mHeight = MeasureSpec.getSize(heightMeasureSpec);
        mHeight = mWidth = mHeight < mWidth ? mHeight : mWidth;
//        初始化imageview
        if (imageViews == null) {
            imageViews = new ImageView[mCount ][mCount];
            newViews = new ImageView[mCount][mCount];
            mGestureLockViewWidth = (int) ( mWidth * 1.0f / (4));
            //计算每个GestureLockView的间距
            mMarginBetweenLockView = (int) (mGestureLockViewWidth * 0.5);
            // 设置画笔的宽度为GestureLockView的内圆直径稍微小点（不喜欢的话，随便设）
//            mPaint.setStrokeWidth((float) mGestureLockViewWidth * 0.29f);
            for (int i = 0;i<mCount;i++) {
                for (int j = 0;j<mCount;j++) {
                    imageViews[i][j] = new ImageView(getContext());
                    imageViews[i][j].setId(i*mCount+j+1);
                    RelativeLayout.LayoutParams params = new LayoutParams(mGestureLockViewWidth, mGestureLockViewWidth);
                    if (j != 0) {
                        params.addRule(RelativeLayout.RIGHT_OF, imageViews[i][j - 1].getId());
                    }
                    if (i != 0) {
                        params.addRule(RelativeLayout.BELOW, imageViews[i - 1][j].getId());
                    }
                    int rightMargin = 0;
                    int bottomMargin = 0;
                    int leftMagin = 0;
                    int topMargin = 0;
                    if (j != 0) {
                        leftMagin = mMarginBetweenLockView;
                    }
                    if (i != 0) {
                        topMargin = mMarginBetweenLockView;
                    }
                    params.setMargins(leftMagin, topMargin, rightMargin, bottomMargin);
                    imageViews[i][j].setImageResource(R.mipmap.o);
                    addView(imageViews[i][j],params);
                }
            }
        }
    }
    /**
     * 检查当前左边是否在child中
     *
     * @param child
     * @param x
     * @param y
     * @return
     */
    private boolean checkPositionInChild(View child, int x, int y) {

        //设置了内边距，即x,y必须落入下GestureLockView的内部中间的小区域中，可以通过调整padding使得x,y落入范围不变大，或者不设置padding
        int padding = (int) (mGestureLockViewWidth * 0.15);

        if (x >= child.getLeft() + padding && x <= child.getRight() - padding
                && y >= child.getTop() + padding
                && y <= child.getBottom() - padding) {
            return true;
        }
        return false;
    }
    /**
     * 通过x,y获得落入的GestureLockView
     *
     * @param x
     * @param y
     * @return
     */
    private ImageView getChildIdByPos(int x, int y) {
        for (int i = 0; i < mCount; i++) {
            for (int j = 0;j<mCount;j++) {

                if (checkPositionInChild(imageViews[i][j], x, y)) {
                    return imageViews[i][j];
                }
            }
        }

        return null;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                ImageView child = getChildIdByPos(x, y);
                if (child != null) {
                    child.setImageResource(R.mipmap.ooo);
                    child.bringToFront();
                    if (!mChoose.contains(child.getId())) {
                        mChoose.add(child.getId());
                        child.setVisibility(VISIBLE);
                        mLastPathX = child.getLeft() / 2 + child.getRight() / 2;
                        mLastPathY = child.getTop() / 2 + child.getBottom() / 2;
                    }
                    if (mChoose.size() == 1) {
                        mPath.moveTo(mLastPathX, mLastPathY);
                    } else {
                        mPath.lineTo(mLastPathX,mLastPathY);
                    }
                    mTmpTarget.x = x;
                    mTmpTarget.y = y;
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        invalidate();
        return true;
    }


    @Override
    public void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        //绘制GestureLockView间的连线
        if (mPath != null) {
            canvas.drawPath(mPath, mPaint);
        }
        //绘制指引线
        if (mChoose.size() > 0) {
            if (mLastPathX != 0 && mLastPathY != 0)
                canvas.drawLine(mLastPathX, mLastPathY, mTmpTarget.x,
                        mTmpTarget.y, mPaint);
        }
//        if (mChoose.size() > 0) {
//            int x = 0, y;
//            Integer integer = mChoose.get(mChoose.size() - 1);
//            if (integer < 4) {
//                x = 0;
//                y = integer - 1;
//            } else if (integer % 3 == 0) {
//                x = integer / 3 - 1;
//                y = 2;
//            } else {
//                x = integer / 3;
//                y = integer % 3 - 1;
//            }
//            LogUtils.loge(integer+"          "+x+"    "+y);
//            imageViews[x][y].bringToFront();
//            RelativeLayout.LayoutParams params = new LayoutParams(mGestureLockViewWidth, mGestureLockViewWidth);
//            params.addRule(RelativeLayout.ALIGN_LEFT, imageViews[x][y].getId());
//            params.addRule(RelativeLayout.ALIGN_TOP, imageViews[x][y].getId());
//            imageViews[x][y].setVisibility(INVISIBLE);
//            newViews[x][y] = new ImageView(getContext());
//            newViews[x][y].setImageResource(R.mipmap.ooo);
//            addView(newViews[x][y],params);
//            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ooo);
//            canvas.drawBitmap(bitmap, imageViews[x][y].getLeft()+(int)( mGestureLockViewWidth*0.25), imageViews[x][y].getTop()+(int)( mGestureLockViewWidth*0.25), mPaint);

        }

}

